import $C from './config.js';
import store from '@/store/index';

export const post = (name = '' , url, data={} , fun = '' ) => {
	return new Promise((resolve, reject) => {
		
		let headers = {}
		
		// 设置请求头参数
		headers['Content-Type'] = 'application/x-www-form-urlencoded'
		
		if(store.state.userinfo.token){
			// 把登录信息追加到请求头中 
			headers['token'] = store.state.userinfo.token
		}
		
		// 发请求
		uni.request({
			url: $C.webUrl + $C.ruleApi + url,
			data: data,
			method:'POST',
			responseType: 'text',
			header:headers,
			success: res => {
				
				if(res.data.code==400400){
					return uni.redirectTo({
						url:'/pages/system/error'
					})
				}
				
				if(res.statusCode==401){
					return uni.redirectTo({
						url:'/pages/home/login'
					})
				}
				
				if(res.data.code==0){
					uni.showToast({
						title:res.data.msg,
						icon:'none'
					});
				}
				
				if(typeof fun == 'function'){
					fun()
				}
				
				if(res.statusCode==403){
					
					if(typeof fun!='string'){
						return uni.showModal({
							title:'系统提示',
							content:'对不起您无权' + name,
							showCancel:false
						})
					}else{
						uni.showToast({
							title:'对不起您无权' + name,
							icon:'none'
						})
					}
					
				}
				
				resolve(res.data);
			},
			fail: err => {
				reject(err)
			}
		});
	})
}


export const upload = (url, data={}, file) => {
	return new Promise((resolve, reject) => {
		
		let headers = {}
		
		// 设置请求头参数
		headers['Content-Type'] = 'application/x-www-form-urlencoded'
		
		if(store.state.userinfo.token){
			// 把登录信息追加到请求头中 
			headers['token'] = store.state.userinfo.token
		}
		uni.uploadFile({
			url: $C.webUrl + $C.ruleApi + url,
			formData: data,
			method:'POST',
			name:'file',
			filePath: file,
			header:headers,
			success: res => {
				resolve(JSON.parse(res.data))
			},
			fail: err => {
				reject(err)
			}
		});
		
	})
}